import React, { useState } from 'react';
import { Modal, Form, Radio, Switch, Input, message } from 'antd';
import FormItem from 'antd/lib/form/FormItem';
import SelectTree from './SelectTree';
import AnalyseCategorySelect from 'src/pages/AnalyseManage/Components/AnalyseCategorySelect';
import {
	createAnalysePage,
	createAnalysePageConfig,
	getAnalysePageConfig,
	updateAnalysePageConfig,
	// getChildAnalysePageList,
} from 'src/services/AnalyseManage';

interface IProps {
	okHandle: Function;
	cancelHandle: Function;
	handleJump: Function;
	modalVisible: boolean;
	currentConfigs: Array<any>;
}

const ORIGIN_CODE = 'origin';
const NEW_CODE = 'new';

const options = [
	{ value: ORIGIN_CODE, label: '已有仪表板' },
	{ value: NEW_CODE, label: '新建' },
];

const AddModal = ( props: IProps ) => {
	const [ form ] = Form.useForm();
	const { okHandle, cancelHandle, modalVisible, currentConfigs } = props;
	const defaultValues: any = { chartType: ORIGIN_CODE };
	const [ formData, setFormData ] = useState( defaultValues );
	// const [ chartList, setChartList ] = useState( [] );

	const onOk = () => {
		form.validateFields()
			.then( async ( values: any ) => {
				if ( values.chartType === ORIGIN_CODE ) {
					originSaveHandle( formData );
				}
				if ( values.chartType === NEW_CODE ) {
					newSaveHandle( formData );
				}
			} )
			.catch( ( errorInfo ) => {} );
	};

	//	新添加的组件，获取y轴最大值
	const getMaxY = ( layoutConfig ) => {
		if ( layoutConfig.length === 0 ) return 0;
		let maxY = 0;

		layoutConfig.forEach( ( v ) => {
			maxY = v.y + v.h > maxY ? v.y + v.h : maxY;
		} );
		return maxY;
	};

	const originSaveHandle = async ( values: any ) => {
		// 如果是选择原有仪表板，则需要先请求原有的config, 添加后，再保存
		let response = await getAnalysePageConfig( { pageId: values.originChartName, type: 'EDIT' } );
		if ( response.data && response.data.success && response.data.data ) {
			const pageConfigs = JSON.parse( response.data.data.content );
			const { children: originChildren = [], layoutConfig = [] } = pageConfigs;

			let newChildren = originChildren,
				newLayoutConfig = layoutConfig,
				isRepeat = false;
			for ( let k in currentConfigs ) {
				const v = currentConfigs[k];
				if ( originChildren.some( ( i ) => i.key === v.key ) ) {
					// 所选报表中如果存在该图形，提示用户已有该图形
					isRepeat = true;
					message.warning( '所选图表中已存在该图形' );
					break;
				} else {
					let newComponentLayout = {
						i: v.key,
						x: 0,
						y: getMaxY( newLayoutConfig ),
						w: 17,
						h: 18,
					};

					newLayoutConfig.push( newComponentLayout );
					newChildren.push( v );
				}
			}

			if ( !isRepeat ) {
				let newPageConfigs = {
					page: {
						...pageConfigs.page,
					},
					children: [ ...newChildren ],
					layoutConfig: [ ...newLayoutConfig ],
				};
				saveConfig( response.data.data, newPageConfigs );
			}
		}
	};

	const newSaveHandle = async ( values: any ) => {
		// 如果是新增仪表板，则需要先新增，再将对应的 config 添加进去
		let response;

		let data = {
			code: values.code,
			des: values.des,
			name: values.name,
			parentId: values.parentId,
			type: 'dashbord',
		};
		response = await createAnalysePage( data );

		if ( response.data && response.data.success ) {
			const resData = response.data.data;

			let newChildren = [],
				newLayoutConfig = [];
			for ( let k in currentConfigs ) {
				const v = currentConfigs[k];

				let newComponentLayout = {
					i: v.key,
					x: 0,
					y: getMaxY( newLayoutConfig ),
					w: 17,
					h: 18,
				};

				newLayoutConfig.push( newComponentLayout );
				newChildren.push( v );
			}

			let newPageConfigs = {
				page: {
					...resData,
					type: 'Page',
					key: resData.key,
				},
				children: [ ...newChildren ],
				layoutConfig: [ ...newLayoutConfig ],
			};
			saveConfig( response.data.data, newPageConfigs );
		}
	};

	// 保存config
	const saveConfig = async ( pageConfig, content ) => {
		const { chartType: type, isJump } = form.getFieldsValue();
		let response;
		if ( type === NEW_CODE ) {
			let data = { pageId: pageConfig.id, content: JSON.stringify( content ) };
			response = await createAnalysePageConfig( data );
		}
		if ( type === ORIGIN_CODE ) {
			let data = { id: pageConfig.id, content: JSON.stringify( content ) };
			response = await updateAnalysePageConfig( data );
			console.log( content );
		}

		if ( response.data && response.data.success && response.data.data ) {
			message.success( '保存成功' );
			okHandle();

			if ( isJump ) {
				// 如果需要跳转则要跳转页面
				props.handleJump( response.data.data.pageId );
			}
		}
	};

	const selectFolder = ( node: any ) => {
		form.setFieldsValue( { parentId: node.id } );
		setFormData( { ...formData, parentId: node.id } );
	};

	const handleFormValuesChange = ( changedvalues ) => {
		setFormData( { ...formData, ...changedvalues } );
	};

	// 已有仪表盘选择文件夹
	const selectOriginFolder = async ( node: any ) => {
		form.setFieldsValue( { originChartId: node.id } );

		setFormData( { ...form.getFieldsValue(), originFolderId: node.parentId, originChartName: node.id } );
		// form.setFieldsValue( { originFolderId: node.id, originChartName: null } );
		// setFormData( { ...form.getFieldsValue() } );
		// let response = await getChildAnalysePageList( {
		// 	categoryId: node.id,
		// 	name: '',
		// 	page: 1,
		// 	size: 9999,
		// } );
		// if ( response.data && response.data.success ) {
		// 	let rows = response.data.data.rows;
		// 	setChartList( rows );
		// }
	};

	return (
		<Modal
			destroyOnClose
			title="添加至仪表板"
			visible={modalVisible}
			width={'40%'}
			okText="确定"
			onOk={onOk}
			onCancel={() => cancelHandle()}
			cancelText="取消"
		>
			<Form preserve={false} form={form} initialValues={formData} onValuesChange={handleFormValuesChange} layout="horizontal">
				<FormItem labelCol={{ span: 5 }} label="类型" name="chartType" rules={[ { required: true, message: '不能为空！' } ]}>
					<Radio.Group options={options}></Radio.Group>
				</FormItem>
				{formData.chartType === ORIGIN_CODE && (
					<>
						<FormItem
							labelCol={{ span: 5 }}
							wrapperCol={{ span: 15 }}
							label="报表名称"
							name="originChartId"
							rules={[ { required: true, message: '不能为空！' } ]}
						>
							<SelectTree
								onSelect={( node ) => {
									selectOriginFolder( node );
								}}
								defaultSelectedKeys={[]}
							></SelectTree>
						</FormItem>
					
						{/* <FormItem
							labelCol={{ span: 5 }}
							wrapperCol={{ span: 15 }}
							label="文件夹结构"
							name="originFolderId"
							rules={[ { required: true, message: '不能为空！' } ]}
						>
							<AnalyseCategorySelect
								onSelect={( node ) => {
									selectOriginFolder( node );
								}}
								defaultSelectedKeys={[]}
							></AnalyseCategorySelect>
						</FormItem>
						<FormItem
							labelCol={{ span: 5 }}
							wrapperCol={{ span: 15 }}
							label="图表名称"
							name="originChartName"
							rules={[ { required: true, message: '不能为空！' } ]}
						>
							<Select
								filterOption={( input, option ) => option.children.toLowerCase().indexOf( input.toLowerCase() ) >= 0}
								showSearch
								allowClear
								placeholder="图表名称不能为空"
							>
								{chartList.map( ( item, index ) => (
									<Select.Option key={index} value={item.id}>
										{item.name}
									</Select.Option>
								) )}
							</Select>
						</FormItem> */}
					</>
				)}
				{formData.chartType === NEW_CODE && (
					<>
						<FormItem
							labelCol={{ span: 5 }}
							wrapperCol={{ span: 15 }}
							label="报表编码"
							name="code"
							rules={[ { required: true, message: '不能为空！' } ]}
						>
							<Input placeholder="编码不能为空，且不可重复" />
						</FormItem>
						<FormItem
							labelCol={{ span: 5 }}
							wrapperCol={{ span: 15 }}
							label="报表名称"
							name="name"
							rules={[ { required: true, message: '不能为空！' } ]}
						>
							<Input placeholder="名称不能为空" />
						</FormItem>
						<FormItem
							labelCol={{ span: 5 }}
							wrapperCol={{ span: 15 }}
							label="请选择文件夹"
							name="parentId"
							rules={[ { required: true, message: '不能为空！' } ]}
						>
							<AnalyseCategorySelect
								onSelect={( node ) => {
									selectFolder( node );
								}}
								defaultSelectedKeys={[]}
							></AnalyseCategorySelect>
						</FormItem>

						<FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="描述" name="des" rules={[ { message: '不能为空！' } ]}>
							<Input />
						</FormItem>
					</>
				)}

				<FormItem labelCol={{ span: 5 }} label="是否跳转" name="isJump">
					<Switch></Switch>
				</FormItem>
			</Form>
		</Modal>
	);
};

export default React.memo( AddModal );
